"""
任务相关数据模型
用于数据库存储的模型定义
"""
from datetime import datetime, timezone
from typing import Any
from enum import Enum
from pydantic import BaseModel, Field, field_validator
from bson import ObjectId
from app.models.base import PyObjectId

# 任务状态通过state模块进行管理，使用字符串类型

class TaskPriority(str, Enum):
    """任务优先级"""
    LOWEST = "lowest"    # 最低
    LOW = "low"          # 低
    MEDIUM = "medium"    # 中
    HIGH = "high"        # 高
    URGENT = "urgent"    # 紧急
    CRITICAL = "critical" # 严重
    BLOCKER = "blocker"  # 阻塞

class TaskType(str, Enum):
    """任务类型"""
    FEATURE = "feature"           # 功能开发
    BUG_FIX = "bug_fix"          # 缺陷修复
    IMPROVEMENT = "improvement"   # 改进
    DOCUMENTATION = "documentation" # 文档
    TESTING = "testing"          # 测试
    RESEARCH = "research"        # 研究
    MAINTENANCE = "maintenance"  # 维护
    OTHER = "other"              # 其他

class TaskComment(BaseModel):
    """任务评论（数据库模型）"""
    id: str = Field(..., description="评论ID")
    user_id: str = Field(..., description="用户ID")
    user_name: str = Field(..., description="用户名称")
    content: str = Field(..., description="评论内容")
    parent_comment_id: str | None = Field(None, description="父评论ID，用于回复功能")
    status: str = Field(default="published", description="评论状态（动态状态）")
    is_deleted: bool = Field(default=False, description="是否已删除（已废弃，使用status字段）")
    created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), description="创建时间")
    updated_at: datetime | None = Field(None, description="更新时间")

class TaskAttachment(BaseModel):
    """任务附件（数据库模型）"""
    id: str = Field(..., description="附件ID")
    filename: str = Field(..., description="文件名")
    original_filename: str = Field(..., description="原始文件名")
    file_size: int = Field(..., description="文件大小")
    file_type: str = Field(..., description="文件类型")
    url: str = Field(..., description="文件URL")
    uploaded_by: str = Field(..., description="上传者ID")
    uploaded_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), description="上传时间")

class TaskTimeLog(BaseModel):
    """任务工时记录（数据库模型）"""
    id: str = Field(..., description="工时记录ID")
    user_id: str = Field(..., description="用户ID")
    user_name: str = Field(..., description="用户名称")
    hours: float = Field(..., ge=0, description="工时")
    description: str | None = Field(None, description="工时描述")
    date: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), description="记录日期")
    created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), description="创建时间")

class TaskBase(BaseModel):
    """任务基础模型"""
    title: str = Field(..., min_length=1, max_length=200, description="任务标题")
    description: str | None = Field(None, max_length=5000, description="任务描述")
    task_type: str = Field(default="feature", description="任务类型")
    status: str = Field(default="", description="任务状态（从状态管理系统动态获取，创建时使用默认状态）")
    priority: str = Field(default="medium", description="任务优先级")
    project_id: PyObjectId = Field(..., description="所属项目ID")
    assignee_id: PyObjectId | None = Field(None, description="负责人ID")
    reporter_id: PyObjectId = Field(..., description="报告人ID")
    parent_task_id: PyObjectId | None = Field(None, description="父任务ID")
    estimated_hours: float | None = Field(None, ge=0, description="预估工时")
    actual_hours: float | None = Field(None, ge=0, description="实际工时")
    start_date: datetime | None = Field(None, description="开始日期")
    due_date: datetime | None = Field(None, description="截止日期")
    tags: list[str] = Field(default_factory=list, description="任务标签")
    
    @field_validator('due_date')
    @classmethod
    def validate_due_date(cls, v: datetime | None, info) -> datetime | None:
        if v and info.data.get('start_date'):
            if v <= info.data['start_date']:
                raise ValueError('Due date must be after start date')
        return v

class TaskInDB(TaskBase):
    """数据库中的任务模型"""
    id: PyObjectId = Field(default_factory=PyObjectId, alias="_id")
    comments: list[TaskComment] = Field(default_factory=list, description="任务评论")
    attachments: list[TaskAttachment] = Field(default_factory=list, description="任务附件")
    time_logs: list[TaskTimeLog] = Field(default_factory=list, description="工时记录")
    watchers: list[PyObjectId] = Field(default_factory=list, description="关注者ID列表")
    created_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), description="创建时间")
    updated_at: datetime = Field(default_factory=lambda: datetime.now(timezone.utc), description="更新时间")
    completed_at: datetime | None = Field(None, description="完成时间")
    
    class Config:
        populate_by_name = True
        arbitrary_types_allowed = True
        json_encoders: dict[type[Any], type[str]] = {ObjectId: str}

class Task(TaskInDB):
    """任务模型（用于内部使用）"""
    pass
